package com.LeeCode;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 描述绘画结果
 */

public class Code1943 {
    public static void main(String[] args) {
        int[][] segments = {
                {1, 4, 5},  {6, 7, 9}
        };
        System.out.println(new Code1943().splitPainting(segments));
    }

    public List<List<Long>> splitPainting(int[][] segments) {
        // 差分：记录每个坐标的变化量
        TreeMap<Integer, Long> diffMap = new TreeMap<>();

        for (int[] seg : segments) {
            int start = seg[0], end = seg[1], color = seg[2];
            diffMap.merge(start, (long) color, Long::sum);
            diffMap.merge(end, (long) -color, Long::sum);
        }

        List<List<Long>> res = new ArrayList<>();

        long currentSum = 0;
        int prevPos = -1;

        for (Map.Entry<Integer, Long> entry : diffMap.entrySet()) {
            int pos = entry.getKey();
            long delta = entry.getValue();

            // 如果之前有颜色，且当前段长度 > 0，则添加区间 [prevPos, pos]
            if (prevPos != -1 && currentSum > 0) {
                res.add(List.of((long) prevPos, (long) pos, currentSum));
            }

            currentSum += delta;
            prevPos = pos;
        }

        return res;
    }
}
